package com.calvin.study.controller;

import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.client.RestTemplate;

import com.calvin.study.entity.User;

@Controller
@RequestMapping("user")
public class UserController {
	
    @Value("${sso.server.url}")
    String ssoServerUrl;
    @Autowired
    RedisTemplate<String, String> redisTemplate;
	
	@GetMapping("index")
	public String index(HttpSession session,@RequestParam(required=false) String loginToken,Model model) {
		//String loginToken = redisTemplate.opsForValue().get("loginToken");
		if(StringUtils.isNotBlank(loginToken)) {
			//去sso服务器获取当前token真正对应的用户信息
            RestTemplate restTemplate = new RestTemplate();
            ResponseEntity<User> forEntity = restTemplate.getForEntity("http://www.ssoserver.com:8080/ssoserver/userInfo?loginToken=" + loginToken, User.class);
            session.setAttribute("loginUser",forEntity.getBody());
		}
		
		//当前session会话中，用户是否已登录
		Object loginUser = session.getAttribute("loginUser");
		if(null == loginUser) {
			//1.用户未登录，则去认证中心登录，将当前url作为参数，认证后跳转到该地址
			return "redirect:" + ssoServerUrl + "?serviceUrl=http://www.user.com:8081/user/index";
		}
		model.addAttribute("user", loginUser);
		return "user_index";
	}

}
